<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件


function get_id()
{
    $uuid = md5(uniqid(mt_rand(), true));
    return $uuid;
}

/**
 * 密码加密方法
 * @param string $pw 要加密的原始密码
 * @param string $authCode 加密字符串
 * @return string
 */
function md5_password($pw, $authCode = '')
{
    if (empty($authCode)) {
        $authCode = 'qMhsKe5rvotHLjcmvl';
    }
    $result = "###" . md5(md5($authCode . $pw));
    return $result;
}


/**
 * 随机字符串生成
 * @param int $len 生成的字符串长度
 * @return string
 */
function random_string($len = 6)
{
    $chars = [
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
        "3", "4", "5", "6", "7", "8", "9"
    ];
    $charsLen = count($chars) - 1;
    shuffle($chars);    // 将数组打乱
    $output = "";
    for ($i = 0; $i < $len; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}


/**
 * 后台API接口数据输出
 * @param $status  业务状态码
 * @param $message 信息提示
 * @param array $data 数据
 * @return \think\response\Json
 */
function show($status, $message, $data)
{
    $data = [
        'status' => $status,
        'message' => $message,
        'data' => $data
    ];
    return json($data);
}

/**
 * 后台API接口数据输出
 * @param $status  业务状态码
 * @param $message 信息提示
 * @param array $data 数据
 * @param int $total 数据总数量，即共多少条数据
 * @return \think\response\Json
 */
function showTotal($status, $message, $data, $total)
{
    $data = [
        'status' => $status,
        'message' => $message,
        'data' => $data,
        'total' => $total
    ];
    return json($data);
}

/**
 * 生成随机验证码
 * @param int $len
 * @return bool|string
 */
function randString($len = 6)
{
    $chars = str_repeat('0123456789', 3);
    // 位数过长重复字符串一定次数
    $chars = str_repeat($chars, $len);
    $chars = str_shuffle($chars);
    $str = substr($chars, 0, $len);

    return $str;
}

function getAreaName($data) {
    if(!$data) {
        return '';
    }
    return \app\admin\model\Area::where('id',$data)->value('name');
}

function getAreaNameByTownId($townId) {
    if(!$townId) {
        return '';
    }
    $AreaTown =  \app\admin\model\Area::where('id',$townId)->find();
    $AreaQu = \app\admin\model\Area::where('id',$AreaTown->parentId)->find();
    $AreaCity = \app\admin\model\Area::where('id',$AreaQu->parentId)->find();

    return [
        'townName'=>$AreaTown->name,
        'xianName'=>$AreaQu->name,
        'cityName'=>$AreaCity->name,
        'cityId' => $AreaCity->id,
        'xianId' => $AreaQu->id,
        'townId' => $townId,
        'villageId' => 0
    ];
}

function getVillageName($data) {
    if(!$data) {
        return '';
    }
    return \app\admin\model\Villages::where('id',$data)->value('name');
}

// 得到所在地
function getArea($data, $qlue = '-'){
    if(!$data['cityId'] || !$data['xianId'] || !$data['townId']){
        return '';
    }
    $ids = $data['cityId'].','.$data['xianId'].','.$data['townId'];
    $area = \app\admin\model\Area::where('id','in',$ids)->field('name')->select();
    $str = [];
    foreach ($area as $v) {
        $str[] = $v['name'];
    }
    if (isset($data['villageId']) && $data['villageId']) {
        $villageName = \app\admin\model\Villages::where('id', $data['villageId'])->value('name');
        $str[] = $villageName;
    }
    $area = implode($qlue, $str);

    return $area;
}


/**
 * 获取客户端IP
 */
function get_IP()
{
    if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")) {
        $ip = getenv("HTTP_CLIENT_IP");
    } else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")) {
        $ip = getenv("HTTP_X_FORWARDED_FOR");
    } else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")){
        $ip = $_SERVER['REMOTE_ADDR'];
    } else {
        $ip = "unknown";
    }

    return  $ip;
}

/**
 * 返回带参数的URL
 *
 * @param $url
 * @return string
 */
function fullUrl($url)
{
    $uriArr = explode('/', $url);
    $params = [];
    if (count($uriArr) >= 3) {
        foreach ($uriArr as $key => $param) {
            if (in_array($key, [0, 1, 2])) {
                continue;
            }
            if ($key % 2 != 0 && isset($uriArr[$key + 1])) {
                $params[$param] = $uriArr[$key + 1];
            }

        }

        return url("$uriArr[0]/$uriArr[1]/$uriArr[2]", $params);
    }

    return url($url);
}

/**
 * 把三维数组转化成二维数组
 */
function array_merge_rec($array)
{
    // 定义一个新的数组
    $newArray = array();
    // 遍历当前数组的所有元素
    foreach ($array as $item) {
        if (is_array($item)) {
            // 如果当前数组元素还是数组的话，就递归调用方法进行合并
            array_merge_rec($item);
            // 将得到的一维数组和当前新数组合并
            $newArray = array_merge($newArray, $item);
        } else {
            // 如果当前元素不是数组，就添加元素到新数组中
            $newArray[] = $item;
        }
    }
    // 修改引用传递进来的数组参数值
    $array = $newArray;

    return $array;
}

/**
 * 二维数组根据某个元素去重
 */
function array_unset($arr, $key){
    // 建立一个目标数组
    $res = array();
    foreach ($arr as $value) {
        $value = (Array)$value;
        // 查看有没有重复项
        if(isset($res[$value[$key]])){
            //有：销毁
            unset($value[$key]);
        }else{
            $res[$value[$key]] = $value;
        }
    }

    return $res;
}

// 二维数组去重
function remove_duplicate($array){
    $result = array();
    foreach($array as $key => $value) {
        $value = (Array)$value;
        $has = false;
        foreach($result as $val){
            if($val['id'] == $value['id']){
                $has = true;
                break;
            }
        }
        if(!$has)
            $result[] = $value;
    }

    return $result;
}


/**
 * 获取订单状态
 * @return array
 */
function get_order_status()
{
    // TODO
    return [
        '1' => '待付款',
        '2' => '待发货',
        '3' => '待收货',
        '4' => '已完成',
        '5' => '已失效',
        '6' => '售后',
        '7' => '已消费',
        '8' => '未消费',
        '9' => '同意售后退款',
        '10' => '拒绝售后退款',
        '11' => '拒绝发货'
    ];
}

// 显示订单状态
function show_order_status($id)
{
    $status = get_order_status();

    return $status[$id];
}

/**
 * 获取状态 （通用）
 * @return array
 */
function get_status()
{
    return [
        '1' => '是',
        '2' => '否'
    ];
}

// 显示状态 （通用）
function show_status($id)
{
    $status = get_status();

    return $status[$id];
}

/**
 * 性别
 * @return array
 */
function get_gender()
{
    return [
        '0' => '未知',
        '1' => '男',
        '2' => '女'
    ];
}

// 显示性别
function show_gender($genderId)
{
    $genders = get_gender();

    return $genders[$genderId];
}

/**
 * 与户主关系
 */
function get_relatedHouseholder()
{
    return [
        '1' => '之母',
        '2' => '之父',
        '3' => '配偶',
        '4' => '之子',
        '5' => '之女',
        '6' => '之儿媳',
        '7' => '之女婿',
        '8' => '之孙子',
        '9' => '之孙女',
        '10' => '之重孙子',
        '11' => '之重孙女',
    ];
}

// 显示与户主关系
function show_relatedHouseholder($id)
{
    $relatedHouseholders = get_relatedHouseholder();

    return $relatedHouseholders[$id];
}

/**
 * 文化程度
 * @return array
 */
function get_education()
{
    return [
        '1' => '研究生',
        '10' => '博士',
        '11' => '硕士',
        '2' => '大学本科',
        '3' => '大学专科',
        '4' => '中专',
        '5' => '高中',
        '6' => '初中',
        '7' => '小学',
        '8' => '文盲',
        '9' => '半文盲'
    ];
}

// 显示文化程度
function show_education($id)
{
    $educations = get_education();

    return $educations[$id];
}

// 贫困属性
function povertydegree()
{
    return [
        '1' => '一般贫困户',
        '2' => '建档立卡贫困户',
        '3' => '五保贫困户',
        '4' => '低保贫困户'
    ];
}

function viewPovertydegree($data)
{
    $povertydegree = povertydegree();

    return $povertydegree[$data];
}

// 致贫原因
function povertyreason()
{
    return [
        '1' => '因病',
        '2' => '因残',
        '3' => '因学',
        '4' => '缺土地',
        '5' => '缺水',
        '6' => '缺技术',
        '7' => '缺劳力',
        '8' => '缺资金',
        '9' => '交通条件落后',
        '10' => '因婚',
        '11' => '自身不足'
    ];
}

function viewPovertyreason($data)
{
    $povertyreason = povertyreason();

    return $povertyreason[$data];
}

// 脱贫属性
function outpoverty()
{
    return [
        '1' => '未脱贫',
        '2' => '已脱贫',
        '3' => '返贫'
    ];
}

function viewOutpoverty($data)
{
    $outpoverty = outpoverty();
    return $outpoverty[$data];
}

//帮扶计划
function aidingplan()
{
    return ['1' => '医疗帮扶', '2' => '种植帮扶', '3' => '养殖帮扶', '4' => '务工就业', '5' => '技术培训', '6' => '金融贷款', '7' => '政策帮扶', '8' => '土地流转', '9' => '产业帮扶', '10' => '捐助慰问', '11' => '加入电商', '12' => '教育帮扶', '13' => '创业帮扶', '14' => '基础设施帮扶'];
}

function viewAidingplan($data)
{
    $aidingplan = aidingplan();
    if (!strrchr($data, ',')) {
        $return[] = $aidingplan[$data];
    } else {
        $data = explode(',', $data);
        $return = [];
        foreach ($data as $v) {
            $return[] = $aidingplan[$v];
        }
        // $return = implode(',', $return);
    }
    return $return;
}

/**
 * 经营主体类型
 */
function get_managetype()
{
    return [
        '1' => '企业',
        '2' => '种养大户',
        '3' => '家庭农场',
        '4' => '普通专业合作社',
        '5' => '集体经济组织合作社',
    ];
}

// 显示经营主体类型
function show_managetype($id)
{
    $managetypes = get_managetype();

    return $managetypes[$id];
}

/**
 * 享受政策
 */
function get_policys()
{
    return [
        '1' => '教育扶贫',
        '2' => '健康扶贫',
        '3' => '农村低保',
        '4' => '就业补助',
        '5' => '危房改造',
        '6' => '雨露计划',
        '7' => '农村五保',
        '8' => '临时救助',
        '9' => '残疾补贴',
        '10' => '小额信贷',
        '11' => '就业奖补',
        '12' => '计生奖补',
        '13' => '金融扶贫',
        '14' => '救灾款',
        '15' => '其他',
    ];
}

// 显示享受政策
function show_policys($id)
{
    $policys = get_policys();

    return $policys[$id];
}

/**
 * 产品单位
 * @return array
 */
function get_product_unit()
{
    return [
        '1' => '斤',
        '2' => '公斤',
        '3' => '两',
        '4' => 'g',
        '5' => 'kg',
        '6' => '只',
        '7' => '个',
        '8' => '片',
        '9' => '枚',
        '10' => '张',
        '11' => '粒',
        '12' => '瓶',
        '13' => '箱',
        '14' => '盒',
        '15' => '包',
        '16' => '罐',
        '17' => '袋',
        '18' => '坛',
        '19' => '桶',
        '20' => '升',
        '21' => '毫升',
        '22' => 'cm',
        '23' => 'mm',
    ];
}

// 显示产品单位
function show_product_unit($id)
{
    $units = get_product_unit();

    return $units[$id];
}

/**
 * 小程序布局内容
 * @return array
 */
function get_layout_content()
{
    return [
        '1' => '头条',
        '2' => '村子',
        //'3' => '村民',
        //'4' => '公告栏',
        '5' => '乡镇机关',
        '6' => '农事知识',
        //'7' => '本地特色',
        '8' => '特色专题',
        '9' => '党务公示',
        '10' => '党建要闻',
        '11' => '党课学习',
        '12' => '考试测评',
        //'13' => '会议',
        '14' => '投票调研',
        '15' => '组织活动',
        '16' => '扶贫动态',
        '17' => '扶贫项目',
        //'18' => '扶贫政策',
        '19' => '一村一品',
        //'20' => '动态',
        '21' => '便民服务',
    ];
}

/**
 * 链接
 * @return array
 */
function get_link()
{
    return [
        '1' => '头条',
        '41' => '头条详情',
        '2' => '村子',
        '42' => '村子详情',
        //'3' => '村民',
        //'4' => '公告栏',
        '5' => '乡镇机关',
        '6' => '农事知识',
        '25' => '知识分类',
        '43' => '知识列表',
        '44' => '知识详情',
        //'7' => '本地特色',
        '8' => '特色专题',
        '45' => '特色专题列表',
        '46' => '特色专题详情',
        '9' => '党务公示',
        '47' => '党务公示详情',
        '10' => '党建要闻',
        '48' => '党建要闻分类',
        '49' => '党建要闻详情',
        '11' => '党课学习',
        '50' => '党课分类',
        '12' => '考试测评',
        //'13' => '会议',
        '14' => '投票调研',
        '15' => '组织活动',
        '16' => '扶贫动态',
        '17' => '扶贫项目',
        //'18' => '扶贫政策',
        //'53' => '扶贫政策详情',
        '19' => '一村一品',
        '51' => '产品分类',
        '52' => '产品详情',
        '20' => '百事通',
        '21' => '便民服务',
        '22' => '智慧党建',
        '23' => '精准扶贫',
        '24' => '产地直供',
    ];
}

// 显示链接名称
function show_link_name($id)
{
    $links = get_link();

    return $links[$id];
}

/**
 * 页面位置
 * @return array
 */
function get_pagesposition()
{
    return [
        //'1' => '首页',
        //'2' => '乡村头条',
        //'3' => '全部村子',
        //'4' => '公告栏',
        '5' => '智慧党建',
        //'6' => '精准扶贫',
        '7' => '一村一品',
        //'8' => '百事通',
        //'9' => '农事知识',
    ];
}

// 显示页面位置
function show_pagesposition($id)
{
    $positions = get_pagesposition();

    return $positions[$id];
}

/**
 * 链接类型
 * @return array
 */
function get_link_type()
{
    return [
        '1' => '首页',
        '2' => '乡村头条',
        '3' => '全部村子',
        '4' => '公告栏',
        '5' => '智慧党建',
        '6' => '精准扶贫',
        '7' => '一村一品',
        '8' => '百事通',
        '9' => '农事知识',
    ];
}

// 显示链接类型
function show_link_type($id)
{
    $linkType = get_link_type();

    return $linkType[$id];
}

/**
 * 课程分类
 * @return array
 */
function get_microclass_category()
{
    return [
        '1' => '党建党章',
        '2' => '习近平讲话',
        '3' => '十九大精神',
        '4' => '三会一课',
        '5' => '治党治国',
        '6' => '党史',
    ];
}

// 显示课程分类
function show_microclass_category($id)
{
    $category = get_microclass_category();

    return $category[$id];
}

/**
 * 显示季度
 */
function show_quarter($data)
{
    $quarter = '';
    switch($data){
        case 1:
            $quarter = '春季';
            break;
        case 2:
            $quarter = '夏季';
            break;
        case 3:
            $quarter = '秋季';
            break;
        case 4:
            $quarter = '冬季';
            break;
        default: break;
    }

    return $quarter;
}

// 显示月份
function show_month($data)
{
    $month = '';
    switch($data){
        case 1:
            $month = '一月';
            break;
        case 2:
            $month = '二月';
            break;
        case 3:
            $month = '三月';
            break;
        case 4:
            $month = '四月';
            break;
        case 5:
            $month = '五月';
            break;
        case 6:
            $month = '六月';
            break;
        case 7:
            $month = '七月';
            break;
        case 8:
            $month = '八月';
            break;
        case 9:
            $month = '九月';
            break;
        case 10:
            $month = '十月';
            break;
        case 11:
            $month = '十一月';
            break;
        case 12:
            $month = '十二月';
            break;
        default: break;
    }

    return $month;
}

/**
 * 农事记账类型(支出/收入)
 */
function get_farmaccounttypes($type)
{
    if($type == 1) {
        // 支出
        return [
            '1' => '种子',
            '2' => '农药',
            '3' => '肥料',
            '4' => '苗木',
            '5' => '地租',
            '6' => '硬件设施',
            '7' => '水电',
            '8' => '人工费',
            '9' => '其他',
        ];
    } else {
        // 收入
        return [
            '1' => '卖货',
            '2' => '卖苗',
            '3' => '政府补贴',
            '4' => '其他',
        ];
    }
}

/**
 * 数字转字母 （生成Excel列标）
 *
 * @param int $index 索引值
 * @param int $start 字母起始值
 * @return string 返回字母
 */
function intToChr($index, $start = 65) {
    $str = '';
    if (floor($index / 26) > 0) {
        $str .= intToChr(floor($index / 26) - 1);
    }

    //echo intToChr(0); // A
    return $str . chr($index % 26 + $start);
}


//根据二维数组某个字段的值查找数组
function filter_by_value ($array, $index, $value){
    $newarray = [];
    if(is_array($array) && count($array)>0)
    {
        foreach(array_keys($array) as $key){
            $temp[$key] = $array[$key][$index];

            if ($temp[$key] == $value){
                $newarray[$key] = $array[$key];
            }
        }
    }
    return $newarray;
}
